package com.gljx.web.controller;

import com.gljx.constant.ActivitiKey;
import com.gljx.util.*;
import com.gljx.web.Entity.*;
import com.gljx.web.service.CustomLogService;
import com.gljx.web.service.DepartmentService;
import com.gljx.web.service.MaintainItemEditService;
import com.gljx.web.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/")
public class MaintainItemEditController {

	//导入activiti工具
	ActitiviUtil activitiUtil = new ActitiviUtil();
	//自动注入
	@Autowired
	private MaintainItemEditService maintainItemEditService;
	//自动注入
	@Autowired
	private DepartmentService departmentService;
	//自动注入
	@Autowired
	private CustomLogService customLogService;

	@Autowired
	private MessageService messageService;

	/**
	 * 查询修改维修项目
	 * @param request
	 * @return
	 */
	@RequestMapping("/queryMaintainItemEdit/look.action")
    public String queryMaintainItemEdit(HttpServletRequest request, String flag) {
        PageBean<MaintainItemEdit> pb = new PageBean<>();
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//时间格式化
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//获取当前时间
		String endTime = sdf.format(new Date());
		//获取前三天
		String beginTime = TimeFormat.getThreeDay();
		try {
			//获取分页
			pb = getPageBean(request,user.getFcompanyid(),beginTime,endTime);
			//获取分页数据
			List<MaintainItemEdit> maintainItemEdits = pb.getBeanList();
			for (MaintainItemEdit maintainItemEdit : maintainItemEdits) {
				//查询子类信息
				List<MaintainItemEditEntry> maintainItemEditEntrys = maintainItemEditService.queryMaintainItemEditEntry(maintainItemEdit.getFid(), "");
				//放入集合
				maintainItemEdit.setMaintainItemEditEntrys(maintainItemEditEntrys);
			}
			//合计信息总条数
			String messageAmount="共有"+pb.getTr()+"条信息";
			//把数据传到页面
			request.setAttribute("messageAmount",messageAmount);
			request.setAttribute("pb", pb);
			request.setAttribute("maintainItemEdits", maintainItemEdits);
			request.setAttribute("beginTime", beginTime);
			request.setAttribute("endTime", endTime);
            request.setAttribute("flag", flag);
        } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/backHome/carManagement/maintainItemEdit/maintainItemEditList";
	}
	
	/**
	 * 根据条件查询修改维修项目
	 * @param request
	 * @param maintainItemName 维修项目
	 * @param beginTime 业务开始时间
	 * @param endTime 业务结束时间
	 * @return
	 */
	@RequestMapping("/queryMaintainItemEditByInfo")
    public String queryMaintainItemEditByInfo(HttpServletRequest request, String maintainItemName, String beginTime, String endTime, String fnumber) {
        PageBean<MaintainItemEdit> pb = new PageBean<>();
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		try {
			//去除空格
			maintainItemName = maintainItemName.trim();
            fnumber = fnumber.trim();
            //获取分页
            pb = getPageBean2(request, user.getFcompanyid(), maintainItemName, beginTime, endTime, fnumber);
            //获取分页数据
			List<MaintainItemEdit> maintainItemEdits = pb.getBeanList();
			for (MaintainItemEdit maintainItemEdit : maintainItemEdits) {
				//查询子类信息
				List<MaintainItemEditEntry> maintainItemEditEntrys = maintainItemEditService.queryMaintainItemEditEntry(maintainItemEdit.getFid(), maintainItemName);
				//放入集合
				maintainItemEdit.setMaintainItemEditEntrys(maintainItemEditEntrys);
			}
			//合计信息总条数
			String messageAmount="共有"+pb.getTr()+"条信息";
			//把数据传到页面
			request.setAttribute("messageAmount",messageAmount);
            request.setAttribute("fnumber", fnumber);
            request.setAttribute("pb", pb);
			request.setAttribute("maintainItemEdits", maintainItemEdits);
			request.setAttribute("maintainItemName", maintainItemName);
			request.setAttribute("beginTime", beginTime);
			request.setAttribute("endTime", endTime);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/backHome/carManagement/maintainItemEdit/maintainItemEditList";
	}
	
	/**
	 * 跳转到添加页面
	 * @param request
	 * @param type
	 * @return
	 */
	@RequestMapping("/insertMaintainItemEdit")
	public String insertMaintainItemEdit(HttpServletRequest request,String type){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//获取部门
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		//获取最大编码
        /*String fnumber = customLogService.selectFunmber("ct_ds_maintainitemedit",user.getFcompanyid());*/
		//获取下一个编码
        String number = GetFnumber.fnumbers("XGWX");
		//获取当前时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//业务时间
		String time = sdf.format(new Date());
		//把数据传到页面
		request.setAttribute("time", time);
		request.setAttribute("type", type);
		request.setAttribute("name", user.getName());
		request.setAttribute("department", department);
		request.setAttribute("fnumber", number);
		return "/backHome/carManagement/maintainItemEdit/editMaintainItemEdit";
	}
	
	/**
	 * 添加或修改
	 * @param request
	 * @param fid
	 * @param maintainItemEdit
	 * @return
	 */
	@RequestMapping("/editMaintainItemEdit")
	public String editMaintainItemEdit(HttpServletRequest request,String fid,MaintainItemEdit maintainItemEdit){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//控制单元id
		maintainItemEdit.setFcontrolunitid(user.getFcompanyid());
		//公司id
		maintainItemEdit.setCfficompanyid(user.getFcompanyid());
		//获取当前时间
		String time = TimeFormat.timeFormat(new Date());
		//操作人id
		maintainItemEdit.setFhandlerid(user.getFid());
		/**获取子类信息集合**/
		//序列
		String[] fseq = request.getParameterValues("fseq");
		//维修项目名称
		//String[] maintainItemName = request.getParameterValues("maintainItemName");
		//维修项目编码
		String[] cfmaintainitemno = request.getParameterValues("cfmaintainitemno");
		//维修项目id
		String[] cfmaintainitemid = request.getParameterValues("cfmaintainitemid");
		//工时
		String[] cfmaintainitemgs = request.getParameterValues("cfmaintainitemgs");
		//单价
		String[] cfmaintainitemdj = request.getParameterValues("cfmaintainitemdj");
		//保修期
		String[] cfmaintainitembxq = request.getParameterValues("cfmaintainitembxq");
		//修改后工时
		String[] cfmigs = request.getParameterValues("cfmigs");
		//修改后单价
		String[] cfmidj = request.getParameterValues("cfmidj");
		//修改后保修期
		String[] cfmibxq = request.getParameterValues("cfmibxq");
		//备注
		String[] cfdesc = request.getParameterValues("cfdesc");
		//添加或修改
		maintainItemEditService.editMaintainItemEdit(maintainItemEdit,fseq,cfmaintainitemno,cfmaintainitemid,cfmaintainitemgs,cfmaintainitemdj,
				cfmaintainitembxq,cfmigs,cfmidj,cfmibxq,cfdesc,user,time);
		if("".equals(fid) || fid == null){
			//添加日志
			customLogService.addLog("车辆管理", time+"对修改维修项目进行添加操作", null, user.getFid());
			//重定向到添加页面
			return "redirect:/DrivingSys/insertMaintainItemEdit?type=3";
		}else{
			//添加日志
			customLogService.addLog("车辆管理", time+"对修改维修项目进行进行修改操作", null, user.getFid());
			//重定向到查询页面
            return "redirect:/DrivingSys/queryMaintainItemEdit/look.action?flag=1";
        }
	}
	
	/**
	 * 根据fid查询
	 * @param request
	 * @param fid
	 * @return
	 */
	@RequestMapping("/queryMaintainItemEditByFid")
	public String queryMaintainItemEditByFid(HttpServletRequest request,String fid){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//查询父类信息
		MaintainItemEdit maintainItemEdit = maintainItemEditService.queryMaintainItemEditByFid(fid);
        if (maintainItemEdit == null) {
            return "/error/not_data";
        } else {
            //查询子类信息
            List<MaintainItemEditEntry> maintainItemEditEntrys = maintainItemEditService.queryMaintainItemEditEntry(fid, "");
            //把数据传到页面
            //查询是否是经办人
            Axamine axamine = new Axamine();
            String state = axamine.selectAuditPersonByAdd(maintainItemEdit.getFnumber().toString(), ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.MODIFYMAINTAINITEM_KEY_GL : ActivitiKey.MODIFYMAINTAINITEM_KEY_NC);
            request.setAttribute("AuditState", state);
            request.setAttribute("activitiBPMN_KEY",ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.MODIFYMAINTAINITEM_KEY_GL : ActivitiKey.MODIFYMAINTAINITEM_KEY_NC);
            request.setAttribute("maintainItemEdit", maintainItemEdit);
            request.setAttribute("maintainItemEditEntrys", maintainItemEditEntrys);
            return "/backHome/carManagement/maintainItemEdit/editMaintainItemEdit";
        }
    }
	
	/**
	 * 根据fid删除
	 * @param request
	 * @param fid
	 * @param deleteId
	 * @return
	 */
	@RequestMapping("/deleteMaintainItemEditByFid")
    public String deleteMaintainItemEditByFid(HttpServletRequest request, String fid, String[] deleteId, String[] fnumber, String fnumber2) {
        //获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//删除
        maintainItemEditService.deleteMaintainItemEditByFid(fid, deleteId, fnumber, fnumber2);
        //添加日志
		customLogService.addLog("车辆管理", TimeFormat.timeFormat(new Date())+"对修改维修项目进行进行删除操作", null, user.getFid());
		//重定向到查询页面
		return "redirect:/DrivingSys/queryMaintainItemEdit/look.action";
	}
	
	/**
	 * 审核，反审核
	 * @param request
	 * @param type 1：审核，2：反审核
	 * @param fid
	 * @return
	 */
	@RequestMapping("/auditMaintainItemEdit")
	@ResponseBody
	public int auditMaintainItemEdit(HttpServletRequest request, String type, String fid, String fnumber, String message, String state, String auditState) {
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//审核，反审核
		int i = maintainItemEditService.auditMaintainItemEdit(fid, type, user.getFid(), fnumber, message, state, auditState);
		//添加日志
		customLogService.addLog("车辆管理", "对修改维修项目进行进行审核操作单据编号 " + fnumber, null, user.getFid());
		return i;
	}

    /**
     * 提交
     *
     * @param fid
     * @return
     */
    @RequestMapping("/submitMaintainItemEdit")
    @ResponseBody
	public int submitMaintainItemEdit(String fid, HttpServletRequest request, String fnumber, String auditState) {
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		MaintainItemEdit maintainItemEdit = new MaintainItemEdit();
		if (!Boolean.valueOf(auditState)) {
			//2.将这个单据编号和你需要保存的流程变量存入map集合中
			Map<String, Object> map = new HashMap<String, Object>();
			map.put(ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.MODIFYMAINTAINITEM_KEY_GL : ActivitiKey.MODIFYMAINTAINITEM_KEY_NC, fnumber);//使用你自己单据的key，或者用默认的
			//3.调用方法 flowKey:指定要启动的流程定义 map流程变量
			String piID = activitiUtil.creatFlow(ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.MODIFYMAINTAINITEM_KEY_GL : ActivitiKey.MODIFYMAINTAINITEM_KEY_NC, map);
			//4.如果你有“提交”这个流程，那么你还要补上一步，将流程推进到提交的下一步
			Message message = activitiUtil.completeFlowByPiID(piID);
			//推送消息给下一步经办人
			if (message != null) {
				message.setMessage("修改维修项目-审核 #" + fnumber + " #");//消息内容
				message.setUrl("/queryMaintainItemEditByFid?fid=" + fid + "");//详细路径
				messageService.insert(message);
			}
		} else {
			Message message2 = activitiUtil.complteFlowByVariable(
					ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.MODIFYMAINTAINITEM_KEY_GL : ActivitiKey.MODIFYMAINTAINITEM_KEY_NC,  //指定要启动的流程定义
					fnumber                    //流程变量
			);
			if (message2 != null) {
				message2.setMessage("修改维修项目-审核 #" + fnumber + " #");//消息内容
				message2.setUrl("/queryMaintainItemEditByFid?fid=" + fid + "");//详细路径
				messageService.insert(message2);
			}
		}
//		//获取操作人信息
//		User user = (User) request.getSession().getAttribute("user");
		maintainItemEdit.setFid(fid);
		maintainItemEdit.setFlastupdateuserid(user.getFid());
		maintainItemEdit.setCfbillstate(4L);
		int i = maintainItemEditService.modifyMaintainItemEdit(maintainItemEdit);
		//添加日志
		customLogService.addLog("车辆管理", "对修改维修项目进行进行提交操作单据编号 " + fnumber, null, user.getFid());
		return i;
    }

    @SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类 
	 * @throws Exception
	 */
    public PageBean<MaintainItemEdit> getPageBean2(HttpServletRequest request, String companyId, String maintainItemName, String beginTime, String endTime, String fnumber) throws Exception {

		int offset;//从第几条数据开始加载
		if(request.getParameter("pager.offset")==null){  
			offset=0;  
		}else{  
			offset=Integer.parseInt(request.getParameter("pager.offset"));  
		}	
		//拼接SQL语句
		StringBuffer psql = new  StringBuffer();
		psql.append("select distinct t.fid,t.fnumber,t.fdescription,to_char(t.fbizdate,'yyyy-MM-dd')fbizdate,u.name createName,us.name auditName,t.cfbillstate from ");
		psql.append(" ct_ds_maintainitemedit t left join t_e_user u  on t.fcreatorid=u.fid left join t_e_user us on t.fauditorid = us.fid ");
		psql.append("left join ct_ds_maintainitemeditentry m on m.fparentid = t.fid left join ct_ds_maintainitem ma on m.cfmaintainitemid = ma.fid ");
		psql.append(" where t.fcontrolunitid = '"+companyId+"'");
		if("".equals(maintainItemName) || maintainItemName == null){
			
		}else{
			psql.append(" and ma.fname_l2 like '%"+maintainItemName+"%'");
		}
        if (fnumber == null || "".equals(fnumber)) {

        } else {
            psql.append(" and t.fnumber like '%" + fnumber + "%'");
        }
        if("".equals(beginTime) || "".equals(endTime)){

		}else{
			psql.append("  and t.fbizdate between to_date('"+beginTime+"','YYYY/MM/DD') and to_date('"+endTime+"','YYYY/MM/DD')");
		}
        psql.append(" order by to_char(t.fbizdate,'yyyy-MM-dd') desc");
        int psize = 100; //每页显示数
        int pindex=offset/psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap= maintainItemEditService.selectPage(pindex, psql.toString(), psize);
		PageBean<MaintainItemEdit> pb=new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount=getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int)paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<MaintainItemEdit>)paramMap.get("v_cur")); //每页数据集
		return pb;
	}
	
	@SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类 
	 * @throws Exception
	 */
	public PageBean<MaintainItemEdit> getPageBean(HttpServletRequest request,String companyId,String beginTime,String endTime) throws Exception
	{

		int offset;//从第几条数据开始加载
		if(request.getParameter("pager.offset")==null){  
			offset=0;  
		}else{  
			offset=Integer.parseInt(request.getParameter("pager.offset"));  
		}	
		//拼接SQL语句
		StringBuffer psql = new  StringBuffer();
		psql.append("select t.fid,t.fnumber,t.fdescription,to_char(t.fbizdate,'yyyy-MM-dd')fbizdate,u.name createName,us.name auditName,t.cfbillstate from ");
		psql.append(" ct_ds_maintainitemedit t left join t_e_user u  on t.fcreatorid=u.fid left join t_e_user us on t.fauditorid = us.fid where t.fcontrolunitid = '"+companyId+"'");
		psql.append(" and t.fbizdate between to_date('"+beginTime+"','YYYY/MM/DD') and to_date('"+endTime+"','YYYY/MM/DD')");
        psql.append(" order by to_char(t.fbizdate,'yyyy-MM-dd') desc");
        int psize = 100; //每页显示数
        int pindex=offset/psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap= maintainItemEditService.selectPage(pindex, psql.toString(), psize);
		PageBean<MaintainItemEdit> pb=new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount=getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int)paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<MaintainItemEdit>)paramMap.get("v_cur")); //每页数据集
		return pb;
	}

	/**
	 * 取记录总数 dmz 20160921
	 * @param psql  SQL语句
	 * @return Map
	 * @throws Exception
	 */
	public Map<String, Object> getPageBeanCount(String psql) throws Exception
	{

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap=maintainItemEditService.selectPageCount(psql);
		return paramMap;		
	}

    /**
     * 导出Excel
     *
     * @param response
     * @param request
     * @param maintainItemName
     * @param beginTime
     * @param endTime
     * @param fnumber
     */
    @RequestMapping("/importMaintainItemEdit")
    public void importMaintainItemEdit(HttpServletResponse response, HttpServletRequest request, String maintainItemName, String beginTime, String endTime, String fnumber) {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        //定义接收类型
        List<Object> data = new ArrayList<>();
        //查询数据
        List<MaintainItemEditEntry> maintainItemEditEntrys = maintainItemEditService.selectMaintainItemEditByInfo(user.getFcompanyid(), maintainItemName.trim(), fnumber.trim(), beginTime, endTime);
        for (MaintainItemEditEntry maintainItemEditEntry : maintainItemEditEntrys) {
            data.add(maintainItemEditEntry.getFnumber());
            data.add(maintainItemEditEntry.getFbizdate());
            data.add(maintainItemEditEntry.getFdescription());
            data.add(maintainItemEditEntry.getShName());
            data.add(maintainItemEditEntry.getZdrName());
            data.add(stateToString.billsState(maintainItemEditEntry.getCfbillstate()));
            data.add(maintainItemEditEntry.getMaintainItemName());
            data.add(maintainItemEditEntry.getCfmaintainitemno());
            data.add(maintainItemEditEntry.getCfmaintainitemgs());
            data.add(maintainItemEditEntry.getCfmaintainitemdj());
            data.add(maintainItemEditEntry.getCfmaintainitembxq());
            data.add(maintainItemEditEntry.getCfmigs());
            data.add(maintainItemEditEntry.getCfmidj());
            data.add(maintainItemEditEntry.getCfmibxq());
            data.add(maintainItemEditEntry.getCfdesc());
        }
        //头部数据
        String head[] = {"单据编号", "业务日期", "参考信息", "审核人名称", "制单人名称", "单据状态", "维修项目", "编码", "工时", "单价", "保修期", "修改后工时", "修改后单价", "修改后保修期", "备注"};
        //长度
        Integer length[] = {8000, 3500, 5000, 3000, 3000, 2800, 8000, 6000, 2600, 2600, 3500, 3000, 3000, 3500, 6000};
        try {
            //导出Excel
            CommonExport.importExcel(response, "修改维修项目" + TimeFormat.getNowTime2() + ".xls", "修改维修项目", data, head, length);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
